package com.roc.web.action.windcontroll;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.MTblInfo;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
/**
 * 导出M表信息
 * @author ml
 *
 */
@Component
@Scope("prototype")
@Namespace("/windControllSta")
public class ExportMtableAction extends PaginationBaseAction{
	
	private Logger logger=LogManager.getLogger(ExportMtableAction.class);
	
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IExcelService excelService;
	
	private ExportMtableSearchCondition searchCondition;
	
	private InputStream excelFile;
	
	@Action(value = "queryMchtJsp", results = { @Result(name = "success", location = "/pages/windControllSta/queryMchtJsp.jsp")
    })
	public String queryMchtJsp(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		
		return SUCCESS;
		}
	
	@Action(value = "queryMchtList", results = { @Result(name = "success", location = "/pages/windControllSta/queryMchtJsp.jsp")
    })
	public String queryMchtList(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		if(searchCondition==null){
			searchCondition=(ExportMtableSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new ExportMtableSearchCondition();
			}
		}
		List<MTblInfo> mtList = new ArrayList<MTblInfo>();
		try {
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			dealTheListSpecially(mtList,searchRsList);
			
			getRequest().setAttribute("mtList", mtList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
		} catch (Exception e) {
			logger.error("M表信息查询异常：{}",e);
		}
		return SUCCESS;
	}
	
	@Action(value="exportMchtList",results = {@Result(name="success",type="stream"
			,params = { "contentType", "text/plain", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.txt",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/windControllSta/queryMchtJsp.jsp") }) 
	public String exportMchtList(){
		if(searchCondition==null){
			searchCondition=(ExportMtableSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new ExportMtableSearchCondition();
			}
		}
		List<MTblInfo> mtList = new ArrayList<MTblInfo>();
	    String enter = "\r\n";         
		try {
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			dealTheListSpecially(mtList,searchRsList);
			
			StringBuffer sb = new StringBuffer();
			if(mtList != null && mtList.size()>0){
				for (int i = 0; i < mtList.size(); i++) {
					MTblInfo m = mtList.get(i);
					sb.append(Constance.Null2EmptyTrim(m.getImportFlag())).append(",")
							.append(Constance.Null2EmptyTrim(m.getMchtCd())).append(",")
							.append(Constance.Null2EmptyTrim(m.getMchtServType())).append(",")
							.append(Constance.Null2EmptyTrim(m.getName())).append(",")
							.append(Constance.Null2EmptyTrim(m.getNameBusi())).append(",")
							.append(Constance.Null2EmptyTrim(m.getBankBelongCd())).append(",")
							.append(Constance.Null2EmptyTrim(m.getNationCd())).append(",")
							.append(Constance.Null2EmptyTrim(m.getAreaCd())).append(",")
							.append(Constance.Null2EmptyTrim(m.getMcc())).append(",")
							.append(Constance.Null2EmptyTrim(m.getOrgType())).append(",")
							.append(Constance.Null2EmptyTrim(m.getStatus())).append(",")
							.append(Constance.Null2EmptyTrim(m.getBusiCertifType())).append(",")
							.append(Constance.Null2EmptyTrim(m.getBusiLiceNo())).append(",")
							.append(Constance.Null2EmptyTrim(m.getBusiAddr())).append(",")
							.append(Constance.Null2EmptyTrim(m.getRegAddr())).append(",")
							.append(Constance.Null2EmptyTrim(m.getEngName())).append(",")
							.append(Constance.Null2EmptyTrim(m.getCertif())).append(",")
							.append(Constance.Null2EmptyTrim(m.getCertifType())).append(",")
							.append(Constance.Null2EmptyTrim(m.getCertifNo())).append(",")
							.append(Constance.Null2EmptyTrim(m.getContactName())).append(",")
							.append(Constance.Null2EmptyTrim(m.getTxAddr())).append(",")
							.append(Constance.Null2EmptyTrim(m.getContactPhone())).append(",")
							.append(Constance.Null2EmptyTrim(m.getPhoneNo())).append(",")
							.append(Constance.Null2EmptyTrim(m.getExtendType())).append(",")
							.append(Constance.Null2EmptyTrim(m.getOutPackOrg())).append(",")
							.append(Constance.Null2EmptyTrim(m.getBankName())).append(",")
							.append(Constance.Null2EmptyTrim(m.getBankAccount())).append(",")
							.append(Constance.Null2EmptyTrim(m.getBankAccountName())).append(",")
							.append(Constance.Null2EmptyTrim(m.getIsSalePrice())).append(",")
							.append(Constance.Null2EmptyTrim(m.getRegCode())).append(",")
							.append(Constance.Null2EmptyTrim(m.getBillingType())).append(",")
							.append(Constance.Null2EmptyTrim(m.getBillingLevel())).append(",")
							.append(Constance.Null2EmptyTrim(m.getDivType())).append(",")
							.append(Constance.Null2EmptyTrim(m.getCreditDivType())).append(",")
							.append(Constance.Null2EmptyTrim(m.getHandFee())).append(",")
							.append(Constance.Null2EmptyTrim(m.getMchtUrl())).append(",")
							.append(Constance.Null2EmptyTrim(m.getSiteName())).append(",")
							.append(Constance.Null2EmptyTrim(m.getPosFunction())).append(",")
							.append(Constance.Null2EmptyTrim(m.getFunctionIntro())).append(",")
							.append(Constance.Null2EmptyTrim(m.getServType())).append(",")
							.append(Constance.Null2EmptyTrim(m.getSingleLimit())).append(",")
							.append(Constance.Null2EmptyTrim(m.getSingleLimitIntro())).append(",")
							.append(Constance.Null2EmptyTrim(m.getCdTotal())).append(",")
							.append(Constance.Null2EmptyTrim(m.getCdTotalIntro())).append(",")
							.append(Constance.Null2EmptyTrim(m.getNetMchtType())).append(",")
							.append(Constance.Null2EmptyTrim(m.getIcpNum())).append(",")
							.append(Constance.Null2EmptyTrim(m.getFlag())).append(",")
							.append(Constance.Null2EmptyTrim(m.getTotalMchtCd())).append(",")
							.append(Constance.Null2EmptyTrim(m.getReceiveCd())).append(",")
							.append(Constance.Null2EmptyTrim(m.getIsOpenNoPwd())).append(",")
							.append(Constance.Null2EmptyTrim(m.getBank())).append(",")
							.append(Constance.Null2EmptyTrim(m.getRemark1())).append(",")
							.append(Constance.Null2EmptyTrim(m.getRemark2())).append(",")
							.append(Constance.Null2EmptyTrim(m.getRemark3())).append(",")
							.append(Constance.Null2EmptyTrim(m.getRemark4())).append(",")
							.append(Constance.Null2EmptyTrim(m.getRemark5())).append(",")
							.append(Constance.Null2EmptyTrim(m.getRemark6())).append(",")
							.append(Constance.Null2EmptyTrim(m.getRemark7())).append(",")
							.append(Constance.Null2EmptyTrim(m.getRemark8())).append(",")
							.append(Constance.Null2EmptyTrim(m.getRemark9())).append(",").append(enter);
				}
				
			}
			logger.info(sb.toString());
			byte[] data = sb.toString().getBytes("UTF-8");
			
			ByteArrayOutputStream output = new ByteArrayOutputStream();  
			output.write(data);
	        byte[] ba = output.toByteArray();  
	        excelFile = new ByteArrayInputStream(ba);  
	        output.flush();  
	        output.close();
	         
		} catch (Exception e) {
			logger.error("M表数据导出异常：",e);
		}
		return SUCCESS;
	}
	

	private void dealTheListSpecially(List<MTblInfo> mtList,
			List<Object> searchRsList) {
		if(searchRsList != null && searchRsList.size()>0){
			Iterator it = searchRsList.iterator();
			while(it.hasNext()){
				Object[] obj = (Object[]) it.next();
				MTblInfo m = new MTblInfo();
				m.setImportFlag(Constance.Null2EmptyTrim(obj[0]));
				m.setMchtCd(Constance.Null2EmptyTrim(obj[1]));
				m.setName(Constance.Null2EmptyTrim(obj[2]));
				m.setNameBusi(Constance.Null2EmptyTrim(obj[3]));
				m.setBankBelongCd(Constance.Null2EmptyTrim(obj[4]));
				m.setAreaCd(Constance.Null2EmptyTrim(obj[5]));
				m.setMcc(Constance.Null2EmptyTrim(obj[6]));
				m.setStatus(Constance.Null2EmptyTrim(obj[7]));
				m.setBusiCertifType("01");
				m.setBusiLiceNo(Constance.Null2EmptyTrim(obj[8]));
				m.setRegAddr(Constance.Null2EmptyTrim(obj[9]));
				m.setCertif(Constance.Null2EmptyTrim(obj[10]));
				m.setCertifType(Constance.Null2EmptyTrim(obj[11]));
				m.setCertifNo(Constance.Null2EmptyTrim(obj[12]));
				m.setContactName(Constance.Null2EmptyTrim(obj[13]));
				m.setTxAddr(Constance.Null2EmptyTrim(obj[14]));
				m.setPhoneNo(Constance.Null2EmptyTrim(obj[15]));
				m.setBillingType(Constance.Null2EmptyTrim(obj[16]));//    t.BILLINGTYPE 特殊计费类型,
				m.setBillingLevel(Constance.Null2EmptyTrim(obj[17]));//    t.BILLINGLEVEL 特殊计费档次,
				m.setExtendType("1");
				mtList.add(m);
			}
			
		}
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_EXPORT_MT_QUERY, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (ExportMtableSearchCondition)getSession().getAttribute(SEARCH_SESSION_EXPORT_MT_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public ExportMtableSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(ExportMtableSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	
	public String getExcelName() {
		String excelName="商户信息"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}


}
